package com.atwisdom.star.thirdInterface.business.Impl;

import com.alibaba.fastjson.JSONObject;
import com.atwisdom.star.common.actionType.InfConfigActionType;
import com.atwisdom.star.common.actionType.modelClass.logic.LogicActionType;
import com.atwisdom.star.common.vo.*;
import com.atwisdom.star.exception.pojo.BusinessException;
import com.atwisdom.star.thirdInterface.business.BaseInfDslService;
import com.atwisdom.star.thirdInterface.business.InfConfigDslService;
import com.atwisdom.star.thirdInterface.pojo.InfConfig;
import com.atwisdom.star.thirdInterface.service.impl.InfConfigServiceImpl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

@Service
public class InfConfigDslServiceImpl extends BaseInfDslService<InfConfig> implements InfConfigDslService {
    private final InfConfigServiceImpl infConfigService;
    public InfConfigDslServiceImpl(InfConfigServiceImpl infConfigService) {
        this.infConfigService = infConfigService;
    }


    /**
     * 服务工厂方法
     * @param actionDataList 参数
     * @return 参数
     * @throws BusinessException 异常
     */
    @Transactional
    public ResultInfo<?> responseFactory(List<ActionData<JSONObject>> actionDataList) throws BusinessException {
        ResultInfo<?> resultInfo = null;
        for (ActionData<JSONObject> actionData : actionDataList) {
            String action = actionData.getAction();
            InfConfigActionType actionType = InfConfigActionType.valueOf(action);
            String methodName = actionType.getMethodName();
            resultInfo = this.execMethod(methodName, actionData);
        }
        return resultInfo;
    }

    /**
     * 反射执行业务方法
     *
     * @param methodName 方法名称
     * @param actionData 接收参数
     * @return 返回统一结果类型(ResultInfo)
     * @throws BusinessException 业务数据异常
     */
    @Override
    public ResultInfo<?> execMethod(String methodName, ActionData<JSONObject> actionData) throws BusinessException {
        Class<? extends InfConfigDslServiceImpl> clz = this.getClass();
        Method method;
        try {
            method = clz.getMethod(methodName, ActionData.class);
            return (ResultInfo<?>) method.invoke(this, actionData);
        }catch(NoSuchMethodException ex){
            throw new BusinessException("999999","没有找到该方法("+methodName+")",ex);
        } catch (IllegalAccessException ex) {
            throw new BusinessException("999999","没有访问该方法权限("+methodName+")",ex);
        } catch (InvocationTargetException ex) {
            Throwable targetException = ex.getTargetException();
            if(targetException instanceof  BusinessException){
                BusinessException bex =  (BusinessException)targetException;
                throw new BusinessException("999999",bex.getErrorMsg(),ex);
            }else{
                throw new BusinessException("999999","出错了请重试：("+methodName+")---"+ex.getMessage(),ex);
            }
        }
    }

    /**
     * 添加模型
     * @param actionData  接收参数
     * @return 返回统一结果类型(ResultInfo )
     */
    @Override
    public ResultInfo<?> add(ActionData<JSONObject> actionData) {
        List<JSONObject> dataList = actionData.getData();
        if(dataList!=null && dataList.size()>0){
            JSONObject jsonObject = dataList.get(0);
            InfConfig infConfig = new InfConfig(jsonObject);
            boolean b =  infConfigService.save(infConfig);
            if(b){
                JSONObject infConfigJsonObject = infConfig.fetchJsonObject();
                return JsonResult.success(infConfigJsonObject);
            }else{
                return JsonResult.error(StatusCode.ERROR_ADD);
            }
        }else{
            return JsonResult.error(StatusCode.ERROR_ADD.getCode(),"没有要添加的数据，添加操作失败！");
        }
    }


    /**
     * 批量添加
     * @param actionData  接收参数
     * @return 返回统一结果类型(ResultInfo )
     */
    @Override
    public ResultInfo<?> batchAdd(ActionData<JSONObject> actionData) {
        List<InfConfig> infConfigs = this.transformActionDataList(actionData);
        boolean b = infConfigService.saveBatch(infConfigs);
        List<JSONObject> jsonObjectList = new ArrayList<>();
        infConfigs.forEach(c-> jsonObjectList.add(c.fetchJsonObject()));
        if(b){
            return JsonResult.success(jsonObjectList);
        }else{
            return JsonResult.error(StatusCode.ERROR_ADD);
        }
    }

    /**
     * 更新
     * @param actionData  接收参数
     * @return 返回统一结果类型(ResultInfo )
     */
    @Override
    public ResultInfo<InfConfig> update(ActionData<JSONObject> actionData) {
        List<JSONObject> dataList = actionData.getData();
        if(dataList!=null && dataList.size()>0){
            InfConfig infConfig = new InfConfig(dataList.get(0));
            boolean b = infConfigService.updateById(infConfig);
            if(b){
                return JsonResult.success(infConfig);
            }else{
                return JsonResult.error(StatusCode.ERROR_UPDATE);
            }
        }else{
            return JsonResult.error(StatusCode.ERROR_UPDATE.getCode(),"没有要更新的数据，更新操作失败！");
        }
    }

    /**
     * 批量更新
     * @param actionData  接收参数
     * @return 返回统一结果类型(ResultInfo )
     */
    @Override
    public ResultInfo<?> batchUpdate(ActionData<JSONObject> actionData) {
        List<InfConfig> infConfigs = transformActionDataList(actionData);
        boolean b = infConfigService.updateBatchById(infConfigs);
        List<JSONObject> jsonObjectList = new ArrayList<>();
        infConfigs.forEach(c-> jsonObjectList.add(c.fetchJsonObject()));
        if(b){
            return JsonResult.success(jsonObjectList);
        }else{
            return JsonResult.error(StatusCode.ERROR_UPDATE);
        }
    }

    /**
     * 删除
     * @param actionData  接收参数
     * @return 返回统一结果类型(ResultInfo )
     */
    @Override
    public ResultInfo<Integer> delete(ActionData<JSONObject> actionData) {
        return this.batchDelete(actionData);
    }

    /**
     * 批量删除
     * @param actionData  接收参数
     * @return 返回统一结果类型(ResultInfo )
     */
    @Override
    public ResultInfo<Integer> batchDelete(ActionData<JSONObject> actionData) {
        if(!this.validActionData(actionData)){
            return JsonResult.error(StatusCode.ERROR_INVALID_DELETE);
        }
        QueryWrapper<InfConfig> queryWrapper = this.buildQueryWrapper(actionData,false);
        int delCount = infConfigService.getBaseMapper().delete(queryWrapper);
        if(delCount >= 1){
            return JsonResult.success(delCount);
        }else{
            return JsonResult.error(StatusCode.ERROR_DELETE);
        }
    }

    /**
     * 根据id数组进行删除
     * @param actionData 参数
     * @return 返回结果
     */
    @Override
    public ResultInfo<Integer> deleteByIds(ActionData<JSONObject> actionData) {
        List<Long> ids = actionData.getIds();
        if(ids==null || ids.size() < 1){
            return JsonResult.error(StatusCode.ERROR_INVALID_DELETE);
        }
        int delCount = infConfigService.getBaseMapper().deleteBatchIds(ids);
        if(delCount >= 1){
            return JsonResult.success(delCount);
        } else {
            return JsonResult.error(StatusCode.ERROR_DELETE);
        }
    }



    /**
     * 不分页查询
     * @param actionData  接收参数
     * @return 返回统一结果类型(ResultInfo )
     */
    @Override
    public ResultInfo<?> query(ActionData<JSONObject> actionData) {
        QueryWrapper<InfConfig> infConfigQueryWrapper = this.buildQueryWrapper(actionData,false);
        this.buildOrderBy(infConfigQueryWrapper, actionData.getOrderBy(),"updateTime");
        List<InfConfig> infConfigs = infConfigService.list(infConfigQueryWrapper);
        List<JSONObject> jsonObjectList = new ArrayList<>();
        infConfigs.forEach(c-> jsonObjectList.add(c.fetchJsonObject()));
        return  JsonResult.success(jsonObjectList);
    }

    @Override
    public List<InfConfig> queryAll() throws BusinessException {
        LambdaQueryWrapper<InfConfig> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(InfConfig::isEnable,true);
        return infConfigService.list(wrapper);
    }

    /**
     * 根据id数组进行简单查询
     *
     * @param actionData 参数
     * @return 返回值
     */
    @Override
    public ResultInfo<?> queryByIds(ActionData<JSONObject> actionData) throws BusinessException {
        List<Long> ids = actionData.getIds();
        List<InfConfig> infConfigs = infConfigService.listByIds(ids);
        List<JSONObject> infConfigJsonObjectList = getInfConfigJsonObjectList(infConfigs);
        return  JsonResult.success(infConfigJsonObjectList);
    }

    @Override
    public ResultInfo<?> queryById(ActionData<JSONObject> actionData) throws BusinessException {
        InfConfig infConfig = infConfigService.getById(actionData.getId());
        JSONObject jsonObject = infConfig.fetchJsonObject();
        return JsonResult.success(jsonObject);
    }

    /**
     * 分页查询，去除复杂字段
     *
     * @param actionData 接收参数
     * @return 返回统一结果类型(ResultInfo)
     */
    @Override
    public ResultInfo<PageInfo>  queryByPage(ActionData<JSONObject> actionData) {
        Page<InfConfig> pageInfo = new Page<>(actionData.getPageNumber(), actionData.getPageSize());
        QueryWrapper<InfConfig> infConfigQueryWrapper = this.buildQueryWrapper(actionData,false);
        this.buildOrderBy(infConfigQueryWrapper, actionData.getOrderBy(),"updateTime");
        return getPageInfoResult(pageInfo,infConfigQueryWrapper);
    }

    public ResultInfo<PageInfo> getPageInfoResult(Page<InfConfig> pageInfo, QueryWrapper<InfConfig> queryWrapper) {
        Page<InfConfig> queryPage = infConfigService.page(pageInfo, queryWrapper);
        List<InfConfig> records = queryPage.getRecords();
        List<JSONObject> jsonObjectList = getInfConfigJsonObjectList(records);
        Page<JSONObject> queryPageDTO = new Page<>();
        BeanUtils.copyProperties(queryPage, queryPageDTO);
        queryPageDTO.setRecords(jsonObjectList);
        PageInfo pageResult = PageInfo.of(queryPageDTO);
        return JsonResult.success(pageResult);
    }

    /**
     * 将模型列表转换为jsonObject 列表
     *
     * @param infConfigs 模型列表
     * @return 返回结果
     */
    public List<JSONObject> getInfConfigJsonObjectList(List<InfConfig> infConfigs) {
        List<JSONObject> jsonList = new ArrayList<>();
        infConfigs.forEach(m -> jsonList.add(m.fetchJsonObject()));
        return jsonList;
    }


    /**
     * 从actionData 取出jsonObject列表 转换成模型列表
     *
     * @param actionData 参数
     * @return 返回模型实体集合
     */
    private List<InfConfig> transformActionDataList(ActionData<JSONObject> actionData) {
        List<JSONObject> jsonObjectList = actionData.getData();
        List<InfConfig> infConfigs = new ArrayList<>();
        jsonObjectList.forEach(j -> {
            InfConfig infConfig = new InfConfig(j);
            infConfigs.add(infConfig);
        });
        return infConfigs;
    }
}
